package com.kangjia.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.http.HttpParam;
import com.kangjia.http.HttpResponse;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

/**
 * 康加api token凭证接口实现类
 * 
 * @author sunshulin
 *
 */
@Service
@Slf4j
public class TokenApiImpl extends AbstractApiImpl {

	
	@Value("${kangjia.token.url}")
	private String url;
	@Value("${kangjia.agentId}")
	private String agentId;
	@Value("${kangjia.agentKey}")
	private String agentKey;
	@Value("${kangjia.secret}")
	private String secret;
	@Value("${kangjia.grantType}")
	private String grantType;
	@Value("${kangjia.version}")
	private String version;

	/**
	 * 获取token
	 * 
	 * @author sunshulin
	 * @throws IOException 
	 * @throws JsonProcessingException 
	 */
	public void getToken() throws JsonProcessingException, IOException {
		List<HttpParam> params = new ArrayList<>();
		params.add(new HttpParam("grantType", grantType));
		params.add(new HttpParam("version", version));
		params.add(new HttpParam("agentId", agentId));
		params.add(new HttpParam("agentKey", agentKey));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		params.add(new HttpParam("reqTime", sdf.format(new Date())));
		HttpResponse response = httpRequest.form(url + "getToken", params);
		JsonNode data = handlerResponse(response, "data");
		if (data != null) {
			JsonNode jsonNode = data.iterator().next();
			String token = jsonNode.get("token").asText();
			log.info("获取康加token={}", token);
			Jedis jedis = jedisPool.getResource();
			jedis.set("kangjia.token", token);
			jedis.expire("kangjia.token", 7200);
			jedis.close();
		} else {
			log.error("请求康加接口getToken出现异常,查看具体日志信息.继续执行获取token");
			try {
				getToken();				
			} catch(Exception e) {
				
			}
		}
	}
}
